<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片裁剪工具</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
</head>
<style type="text/css">
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: Arial, sans-serif;
        background-color: #f0f2f5;
        padding: 10px;
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        display: flex;
        gap: 20px;
    }

    .upload-section,
    .result-section {
        background: white;
        padding: 15px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .upload-section {
        flex: 1;
    }

    .result-section {
        flex: 2;
    }

    h2 {
        margin-bottom: 15px;
        color: #333;
        font-size: 1.2rem;
    }

    .upload-area {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .upload-item {
        border: 1px solid #ddd;
        border-radius: 8px;
        overflow: hidden;
        padding: 10px;
    }

    .upload-header {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 10px;
    }

    .upload-btn {
        background-color: #4CAF50;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: background-color 0.3s;
        position: relative;
    }

    .upload-btn:hover {
        background-color: #45a049;
    }

    .upload-btn input[type="file"] {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        opacity: 0;
        cursor: pointer;
    }

    .file-name {
        flex: 1;
        font-size: 14px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .preview-image {
        width: 100%;
        height: 150px;
        border-radius: 4px;
        overflow: hidden;
        cursor: pointer;
        background-size: contain;
        background-position: center;
        background-repeat: no-repeat;
        transition: transform 0.2s;
        border: 1px solid #eee;
    }

    .preview-image:hover {
        transform: scale(1.05);
    }

    .grid-container {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
        margin-top: 15px;
    }

    .grid-item {
        aspect-ratio: 1;
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        overflow: hidden;
        cursor: pointer;
        transition: transform 0.2s;
    }

    .grid-item:hover {
        transform: scale(1.05);
    }

    .grid-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    /* 下载按钮容器 */
    .download-all-container {
        max-width: 1200px;
        margin: 20px auto;
        text-align: center;
    }

    .download-all-btn {
        background-color: #4CAF50;
        color: white;
        border: none;
        padding: 12px 24px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        transition: background-color 0.3s;
        width: 100%;
        max-width: 300px;
    }

    .download-all-btn:hover {
        background-color: #45a049;
    }

    /* 预览模态框样式 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.8);
        z-index: 1000;
    }

    .modal-content {
        position: relative;
        width: 90%;
        max-width: 800px;
        margin: 20px auto;
        background: white;
        padding: 20px;
        border-radius: 8px;
    }

    .close-modal {
        position: absolute;
        right: 10px;
        top: 10px;
        font-size: 24px;
        cursor: pointer;
        color: #666;
    }

    .preview-images {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10px 0;
    }

    .preview-images img {
        max-width: 100%;
        max-height: 80vh;
        object-fit: contain;
    }

    /* 模态框下载按钮样式 */
    .modal-actions {
        display: flex;
        justify-content: center;
        margin-top: 10px;
        gap: 10px;
    }

    .modal-download-btn {
        background-color: #4CAF50;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: background-color 0.3s;
    }

    .modal-download-btn:hover {
        background-color: #45a049;
    }

    /* 移动端适配 */
    @media (max-width: 768px) {
        body {
            padding: 5px;
        }

        .container {
            flex-direction: column;
            gap: 10px;
        }

        .upload-section,
        .result-section {
            width: 100%;
            padding: 10px;
        }

        h2 {
            font-size: 1.1rem;
            margin-bottom: 10px;
        }

        .upload-box {
            padding: 12px;
        }

        .preview-image {
            height: 120px;
        }

        .grid-container {
            gap: 5px;
        }

        .file-name {
            font-size: 12px;
        }

        .download-all-btn {
            padding: 15px;
            font-size: 18px;
        }

        .modal-content {
            width: 95%;
            margin: 10px auto;
            padding: 15px;
        }
    }
</style>

<body>
    <div class="container">
        <div class="upload-section">
            <h2>图片上传区域</h2>
            <div class="upload-area">
                <div class="upload-item" id="upload1">
                    <div class="upload-header">
                        <div class="upload-btn">
                            <input type="file" accept="image/*" onchange="handleFileSelect(event, 0)">
                            选择图片 1
                        </div>
                        <div class="file-name"></div>
                    </div>
                    <div class="preview-image" style="display: none;"></div>
                </div>
                <div class="upload-item" id="upload2">
                    <div class="upload-header">
                        <div class="upload-btn">
                            <input type="file" accept="image/*" onchange="handleFileSelect(event, 1)">
                            选择图片 2
                        </div>
                        <div class="file-name"></div>
                    </div>
                    <div class="preview-image" style="display: none;"></div>
                </div>
                <div class="upload-item" id="upload3">
                    <div class="upload-header">
                        <div class="upload-btn">
                            <input type="file" accept="image/*" onchange="handleFileSelect(event, 2)">
                            选择图片 3
                        </div>
                        <div class="file-name"></div>
                    </div>
                    <div class="preview-image" style="display: none;"></div>
                </div>
            </div>
        </div>

        <div class="result-section">
            <h2>九宫格效果演示</h2>
            <div class="grid-container">
                <div class="grid-item" id="grid1" onclick="previewGrid(0)"></div>
                <div class="grid-item" id="grid2" onclick="previewGrid(1)"></div>
                <div class="grid-item" id="grid3" onclick="previewGrid(2)"></div>
                <div class="grid-item" id="grid4" onclick="previewGrid(3)"></div>
                <div class="grid-item" id="grid5" onclick="previewGrid(4)"></div>
                <div class="grid-item" id="grid6" onclick="previewGrid(5)"></div>
                <div class="grid-item" id="grid7" onclick="previewGrid(6)"></div>
                <div class="grid-item" id="grid8" onclick="previewGrid(7)"></div>
                <div class="grid-item" id="grid9" onclick="previewGrid(8)"></div>
            </div>
        </div>
    </div>

    <!-- 全局下载按钮 -->
    <div class="download-all-container">
        <button class="download-all-btn" onclick="downloadAllImages()">下载全部图片</button>
    </div>

    <!-- 预览模态框 -->
    <div class="modal" id="previewModal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeModal()">&times;</span>
            <div class="preview-images" id="previewContainer"></div>
            <div class="modal-actions">
                <button class="modal-download-btn" onclick="downloadCurrentImage()">下载当前图片</button>
            </div>
        </div>
    </div>

    <script>
        let uploadedImages = [null, null, null];
        let croppedImages = [[], [], []]; // 存储裁剪后的图片数据
        let currentPreviewUrl = ''; // 用于存储当前预览的图片URL
        const gridItems = Array.from({ length: 9 }, (_, i) => document.getElementById(`grid${i + 1}`));

        function handleFileSelect(event, index) {
            const file = event.target.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = new Image();
                    img.onload = function () {
                        uploadedImages[index] = img;
                        // 显示文件信息和预览图
                        const uploadItem = document.querySelector(`#upload${index + 1}`);
                        const fileName = uploadItem.querySelector('.file-name');
                        const previewImage = uploadItem.querySelector('.preview-image');

                        if (fileName && previewImage) {
                            fileName.textContent = file.name;
                            previewImage.style.backgroundImage = `url(${e.target.result})`;
                            previewImage.style.display = 'block';

                            // 添加预览点击事件
                            previewImage.onclick = () => previewOriginal(e.target.result);
                        }

                        // 处理裁剪
                        cropAndDisplayImage(index);
                    };
                    img.src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        }

        function cropAndDisplayImage(index) {
            const img = uploadedImages[index];
            if (!img) return;

            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            // 计算每个部分的宽度
            const partWidth = img.width / 3;
            const height = img.height;

            // 设置画布大小为原始图片高度
            canvas.width = partWidth;
            canvas.height = height;

            // 清空之前的裁剪结果
            croppedImages[index] = [];

            // 裁剪并显示三个部分
            for (let i = 0; i < 3; i++) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);

                // 绘制对应部分
                ctx.drawImage(
                    img,
                    i * partWidth, 0,      // 源图像的起始x,y坐标
                    partWidth, height,     // 源图像的宽度和高度
                    0, 0,                  // 目标canvas的起始x,y坐标
                    partWidth, height      // 目标canvas的宽度和高度
                );

                // 将裁剪后的图片显示在对应的网格位置
                const gridIndex = index * 3 + i;
                const croppedImage = new Image();
                const imageData = canvas.toDataURL('image/jpeg', 1.0);
                croppedImage.src = imageData;
                croppedImages[index].push(imageData);

                // 清除之前的内容并添加新图片
                gridItems[gridIndex].innerHTML = '';
                gridItems[gridIndex].appendChild(croppedImage);
            }
        }

        function previewOriginal(imageUrl) {
            const modal = document.getElementById('previewModal');
            const container = document.getElementById('previewContainer');
            container.innerHTML = '';

            // 创建大图预览
            const previewImg = document.createElement('img');
            previewImg.src = imageUrl;
            container.appendChild(previewImg);

            // 保存当前预览的图片URL
            currentPreviewUrl = imageUrl;

            modal.style.display = 'block';
        }

        function previewGrid(gridIndex) {
            const img = gridItems[gridIndex].querySelector('img');
            if (!img) return;

            const modal = document.getElementById('previewModal');
            const container = document.getElementById('previewContainer');
            container.innerHTML = '';

            // 创建大图预览
            const previewImg = document.createElement('img');
            previewImg.src = img.src;
            container.appendChild(previewImg);

            // 保存当前预览的图片URL
            currentPreviewUrl = img.src;

            modal.style.display = 'block';
        }

        function downloadCurrentImage() {
            if (!currentPreviewUrl) {
                alert('没有可下载的图片');
                return;
            }

            // 创建下载链接
            const link = document.createElement('a');
            link.href = currentPreviewUrl;
            
            // 从URL中提取文件名，如果没有则使用默认名称
            const fileName = 'image.jpg';
            link.download = fileName;
            
            // 触发下载
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        function downloadAllImages() {
            // 检查是否有图片可以下载
            let hasImages = false;
            for (let images of croppedImages) {
                if (images.length > 0) {
                    hasImages = true;
                    break;
                }
            }

            if (!hasImages) {
                alert('请先上传图片');
                return;
            }

            // 创建一个zip文件
            const zip = new JSZip();

            // 添加所有裁剪后的图片到zip
            croppedImages.forEach((imageGroup, groupIndex) => {
                imageGroup.forEach((dataUrl, imageIndex) => {
                    const base64Data = dataUrl.split(',')[1];
                    zip.file(`group${groupIndex + 1}_image${imageIndex + 1}.jpg`, base64Data, { base64: true });
                });
            });

            // 生成��下载zip文件
            zip.generateAsync({ type: 'blob' }).then(function (content) {
                const link = document.createElement('a');
                link.href = URL.createObjectURL(content);
                link.download = 'all_cropped_images.zip';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }).catch(function (error) {
                console.error('下载出错:', error);
                alert('下载失败，请重试');
            });
        }

        function closeModal() {
            const modal = document.getElementById('previewModal');
            modal.style.display = 'none';
            currentPreviewUrl = ''; // 清除当前预览的URL
        }

        // 点击模态框外部关闭
        window.onclick = function (event) {
            const modal = document.getElementById('previewModal');
            if (event.target == modal) {
                modal.style.display = 'none';
                currentPreviewUrl = ''; // 清除当前预览的URL
            }
        }

        // 添加拖放功能
        document.querySelectorAll('.upload-item').forEach((item, index) => {
            const fileInput = item.querySelector('input[type="file"]');

            item.addEventListener('dragover', (e) => {
                e.preventDefault();
                item.style.backgroundColor = '#f5f5f5';
            });

            item.addEventListener('dragleave', (e) => {
                e.preventDefault();
                item.style.backgroundColor = 'transparent';
            });

            item.addEventListener('drop', (e) => {
                e.preventDefault();
                item.style.backgroundColor = 'transparent';
                
                const file = e.dataTransfer.files[0];
                if (file && file.type.startsWith('image/')) {
                    fileInput.files = e.dataTransfer.files;
                    handleFileSelect({ target: fileInput }, index);
                }
            });
        });
    </script>
</body>

</html>